package com.eastfair.pay.service.impl;

import cn.hutool.core.util.StrUtil;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.annotation.annotation.cache.Cache;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.database.mybatis.conditions.Wraps;
import com.eastfair.database.mybatis.conditions.query.QueryWrap;
import com.eastfair.pay.dao.CollectionAccountMapper;
import com.eastfair.pay.dto.CollectionAccountDTO;
import com.eastfair.pay.dto.CollectionAccountPageQuery;
import com.eastfair.pay.dto.CollectionAccountSaveDTO;
import com.eastfair.pay.entity.CollectionAccount;
import com.eastfair.pay.entity.MerchantSystem;
import com.eastfair.pay.enums.CompanyAccountTypeEnum;
import com.eastfair.pay.exceptioncode.PayExceptionCode;
import com.eastfair.pay.service.CollectionAccountService;
import com.eastfair.pay.service.MerchantSystemService;
import com.eastfair.pay.vo.CollectionAccountVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 业务实现类
 * 收款账户
 * </p>
 *
 * @author clm
 * @date 2023-02-22
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class CollectionAccountServiceImpl extends SuperServiceImpl<CollectionAccountMapper, CollectionAccount> implements CollectionAccountService {

    @Resource
    private MerchantSystemService merchantSystemService;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<CollectionAccount> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }

    /**
     * 通用查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    public List<CollectionAccount> list(CollectionAccountDTO modelDTO, List<Long> ids) {
        return ((CollectionAccountService) AopContext.currentProxy()).listOfCache(modelDTO, ids);
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
            magic = @Magic(
                    key = "{" +
                            "{'isEnabled', #args[0]?.isEnabled}," +
                            "{'companyName', #args[0]?.companyName}," +
                            "{'companyAccountType', #args[0]?.companyAccountType}," +
                            "{'merchantNum', #args[0]?.merchantNum}," +
                            "{'bank', #args[0]?.bank}," +
                            "{'bankcardNum', #args[0]?.bankcardNum}," +
                            "{'id', #args[1]}" +
                            "}"))
    public List<CollectionAccount> listOfCache(CollectionAccountDTO modelDTO, List<Long> ids) {
        //查询
        CollectionAccount queryModel = new CollectionAccount();
        if (modelDTO != null) {
            BeanUtils.copyProperties(modelDTO, queryModel);
        }
        QueryWrap<CollectionAccount> wrapper = Wraps.q(queryModel);
        if (ids != null && !ids.isEmpty()) {
            wrapper.lambda().in(CollectionAccount::getId, ids);
        }
        //添加其他业务查询条件
        wrapper.lambda().eq(CollectionAccount::getIsDeleted, BusinessConstant.DELETE_NO);
        List<CollectionAccount> modelList = list(wrapper);
        return modelList;
    }

    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(CollectionAccount model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setTenantId(ContextUtil.getTenantId());
        return R.successDef();
    }

    /**
     * @param params
     * @return com.eastfair.core.base.R<com.baomidou.mybatisplus.extension.plugins.pagination.Page < com.eastfair.pay.vo.CollectionAccountVO>>
     * @Author clm
     * @Description //分页查询收款账户
     * @Date 10:15 2023/2/22
     * @Param [params]
     */
    @Override
    public Page<CollectionAccountVO> queryList(PageParams<CollectionAccountPageQuery> params) {
        CollectionAccountPageQuery model = params.getModel();

        LambdaQueryWrapper<CollectionAccount> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StrUtil.isNotBlank(model.getCompanyName()), CollectionAccount::getCompanyName, model.getCompanyName());
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(model.getCompanyAccountType()), CollectionAccount::getCompanyAccountType, model.getCompanyAccountType());
        lambdaQueryWrapper.between(model.getCreateStartTime() != null && model.getCreateEndTime() != null, CollectionAccount::getCreateTime, model.getCreateStartTime(), model.getCreateEndTime());
        lambdaQueryWrapper.eq(CollectionAccount::getIsDeleted, BusinessConstant.DELETE_NO);
        //参数转化
        Page<CollectionAccount> accountPage = params.buildPage();
        //查询
        Page<CollectionAccount> account = page(accountPage, lambdaQueryWrapper);
        //实体转化
        Page<CollectionAccountVO> collectionAccountVOPage = ConvertUtil.convertPage(account, CollectionAccountVO.class);

        return collectionAccountVOPage;
    }

    @Override
    public CollectionAccount getAccountByName(String name) {
        LambdaQueryWrapper<CollectionAccount> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CollectionAccount::getCompanyName, name);
        lambdaQueryWrapper.eq(CollectionAccount::getIsDeleted, BusinessConstant.DELETE_NO);
        return baseMapper.selectOne(lambdaQueryWrapper);

    }

    @Override
    public void delete(CollectionAccount collectionAccount) {
        MerchantSystem merchantSystem = merchantSystemService.getByBindMerchantId(collectionAccount.getId());
        if (merchantSystem != null) {
            throw BizException.wrap(PayExceptionCode.MERCHANT_IS_USED);
        }

        collectionAccount.setIsDeleted(BusinessConstant.YES);
        updateById(collectionAccount);
    }

    /**
     * @Author fwl
     * @Description //通过系统标识获取收款账户
     * @Date 15:58 2023/3/24
     * @Param [systemScene]
     **/
    @Override
    public String getCollectionAccountBySystemScene(String systemScene) {
        MerchantSystem merchantSystem = merchantSystemService.getBySystemCode(systemScene);
        if (merchantSystem != null) {
            return merchantSystem.getBindMerchant();
        }
        return null;
    }

    @Override
    public CollectionAccount saveCollectionAccount(CollectionAccountSaveDTO collectionAccountSaveDTO) {
        if (StrUtil.isBlank(collectionAccountSaveDTO.getCompanyName())) {
            throw new BizException("收款单位名称不能为空");
        }
        if (CompanyAccountTypeEnum.MAIN_MERCHANT.getCode().equals(collectionAccountSaveDTO.getCompanyAccountType())) {
            Integer mainMerchantCount = lambdaQuery().eq(CollectionAccount::getCompanyAccountType, CompanyAccountTypeEnum.MAIN_MERCHANT.getCode())
                    .eq(CollectionAccount::getIsDeleted, BusinessConstant.DELETE_NO)
                    .eq(CollectionAccount::getIsEnabled, BusinessConstant.ENABLE_YES).count();
            if (mainMerchantCount > 0) {
                throw new BizException("只能有一个主商户,请勿重复添加");
            }
        }
        Integer count = lambdaQuery().eq(CollectionAccount::getCompanyName, collectionAccountSaveDTO.getCompanyName())
                .eq(CollectionAccount::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(CollectionAccount::getIsEnabled, BusinessConstant.ENABLE_YES).count();
        if (count > 0) {
            throw new BizException("收款单位已存在,请勿重复添加");
        }
        CollectionAccount account = new CollectionAccount();
        BeanUtils.copyProperties(collectionAccountSaveDTO, account);
        save(account);
        return account;
    }

    /**
     * do转vo
     *
     * @param model model
     * @return modelVo
     */
    @Override
    public CollectionAccountVO doToVo(CollectionAccount model) {
        CollectionAccountVO modelVo = new CollectionAccountVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }

    /**
     * do转vo
     *
     * @param modelList modelList
     * @return list
     */
    @Override
    public List<CollectionAccountVO> doToVos(List<CollectionAccount> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return null;
        }
        List<CollectionAccountVO> result = new ArrayList<>();
        for (CollectionAccount model : modelList) {
            result.add(doToVo(model));
        }
        return result;
    }
}
